package com.flame.user.service;

import java.util.List;
import java.util.stream.Collectors;

import com.flame.user.entity.OrgInfo;
import com.flame.user.entity.SimpleUserInfo;
import com.flame.user.exception.UserExceptionMessage;
import com.flame.user.exception.UserRuntimeException;
import com.flame.user.mapper.OrgInfoMapper;
import com.flame.user.mapper.UserInfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * flame_org_info 组织机构表
 *
 * @author 吴欣童
 * @since 2023-02-07 17:41:59
 */
@Service
public class OrgInfoService {

    @Autowired
    private OrgInfoMapper orgInfoMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    public void addOrgInfo(OrgInfo orgInfo) {
        OrgInfo dbOrgInfo = orgInfoMapper.findById(orgInfo.getOrgCode());
        if (dbOrgInfo != null) {
            throw new UserRuntimeException(UserExceptionMessage.ORGINFO_EXIST);
        }
        orgInfoMapper.insert(orgInfo);
    }

    public void updateOrgInfo(OrgInfo orgInfo) {
        orgInfoMapper.updateById(orgInfo);
    }

    public void deleteOrgInfo(String orgCode) {
        List<OrgInfo> list = orgInfoMapper.listByOrgParent(orgCode);
        if (list != null && list.size() > 0) {
            for (OrgInfo orgInfo : list) {
                deleteOrgInfo(orgInfo.getOrgCode());
            }
        }
        orgInfoMapper.deleteById(orgCode);
    }

    public List<OrgInfo> listOrgInfo() {
        return orgInfoMapper.list();
    }

    public List<SimpleUserInfo> listOrgUser(String orgCode) {
        return userInfoMapper.listByOrgCode(orgCode).stream().map(userInfo -> {
            SimpleUserInfo simpleUserInfo = new SimpleUserInfo();
            BeanUtils.copyProperties(userInfo, simpleUserInfo);
            return simpleUserInfo;
        }).collect(Collectors.toList());
    }
}
